package com.robusta.cityuate.fragments;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.MenuItem;
import com.robusta.cityuate.R;
import com.robusta.cityuate.activities.ManageMyspotsActivity;
import com.robusta.cityuate.adapters.SpotsListAdapter;
import com.robusta.cityuate.base.ViewType;
import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.HTTPService;
import com.robusta.cityuate.services.SpotsListService;
import com.robusta.cityuate.utils.ConnectionUtils;

public class FavoriteListFragment extends SherlockListFragment {

	public static final String TYPE_INDEX = null;
	public static final String FAV_TAG = ManageMyspotsActivity.class.getName()
			+ "_FAVSPOT";
	public static final String REPORT_TAG = ManageMyspotsActivity.class.getName()
			+ "_REPSPOT";

	private SpotsListAdapter adapter;

//	private int typeIndex; // 0 maps to all, 1 to my spots & 2 maps to Favorites
	//public String spotsTypes[] = { "ALL_SPOTS", "MY_SPOT", "FAVORITS" };

	public String GET_TAG = FavoriteListFragment.class.getName() + "_GETLIST";

	private Context mContext;

	private CityuateBroadCastReceiver getListReceiver = new CityuateBroadCastReceiver() {
		@Override
		public void onSuccess() {
			fillSpotsList();
		}

		@Override
		public void onFailure() {
			spotsListFuilure();
		}

		@Override
		public void onCancel() {

		}
	};
	
	private CityuateBroadCastReceiver favReceiver = new CityuateBroadCastReceiver() {
		@Override
		public void onSuccess() {

			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext, R.string.spot_unfavorited, Toast.LENGTH_SHORT).show();
			reloadList();
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}

		@Override
		public void onFailure() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			// progressBar.setVisibility(View.GONE);
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, FAV_TAG),
					Toast.LENGTH_SHORT).show();
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}

		@Override
		public void onCancel() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}
	};
	
	private CityuateBroadCastReceiver reportReceiver = new CityuateBroadCastReceiver() {
		@Override
		public void onSuccess() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			// progressBar.setVisibility(View.GONE);
			Toast.makeText(mContext,
					mContext.getResources().getString(R.string.report_succ),
					Toast.LENGTH_SHORT).show();
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}

		@Override
		public void onFailure() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			// progressBar.setVisibility(View.GONE);
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, REPORT_TAG),
					Toast.LENGTH_SHORT).show();
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}

		@Override
		public void onCancel() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}
	};

	private ProgressBar progressBar;
	private LinearLayout listPart;
	private LinearLayout fragmentView;
	private Button retryBtn;

	public static FavoriteListFragment getInstant(Context ctx, int type) {
		FavoriteListFragment n = new FavoriteListFragment();
		n.mContext = ctx;
		Bundle b = new Bundle();
		b.putInt(FavoriteListFragment.TYPE_INDEX, type);
		n.setArguments(b);
		return n;
	}

	public SpotsListAdapter getAdapter() {
		return adapter;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d("Fragment", "onCreateView called");
		fragmentView = (LinearLayout) inflater.inflate(
				R.layout.spots_list_fragment_view, container, false);
		// show retry button
		retryBtn = new Button(mContext);
		retryBtn.setText(R.string.retry);
		retryBtn.setVisibility(View.GONE);
		fragmentView.addView(retryBtn);
		retryBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

				// fragmentView.removeView(retryBtn);
				retryBtn.setVisibility(View.GONE);
				ConnectionUtils.clearConnection(mContext, GET_TAG);
				getSpotsList();

			}
		});
		progressBar = (ProgressBar) fragmentView
				.findViewById(R.id.spots_loading);
		listPart = (LinearLayout) fragmentView.findViewById(R.id.list_part);
		return fragmentView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		registerForContextMenu(getListView());
		getListView().setItemsCanFocus(false);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		setHasOptionsMenu(true);
		adapter = new SpotsListAdapter(mContext,ViewType.Type.RENTER);
		setListAdapter(adapter);
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		mContext = activity;
		super.onAttach(activity);
	}

	@Override
	public void onPause() {
		super.onPause();
		mContext.unregisterReceiver(getListReceiver);
		mContext.unregisterReceiver(favReceiver);
		mContext.unregisterReceiver(reportReceiver);

		if (!ConnectionUtils.isConnecting(mContext, REPORT_TAG)) {
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}

		if (!ConnectionUtils.isConnecting(mContext, FAV_TAG)) {
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}


	}

	@Override
	public void onResume() {
		// register the receiver
		IntentFilter filter = new IntentFilter(GET_TAG);
		mContext.registerReceiver(getListReceiver, filter);

		getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
				false);

		if (ConnectionUtils.isConnecting(mContext, GET_TAG)||ConnectionUtils.isConnecting(mContext, FAV_TAG)
				|| ConnectionUtils.isConnecting(mContext, REPORT_TAG)) {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
			// Log.d(GET_TAG, "OnResume Active Connection");
			progressBar.setVisibility(View.VISIBLE);
		} else {
			if (ConnectionUtils.wasConnected(mContext, GET_TAG))
				if (ConnectionUtils.isResultSuccessful(mContext, GET_TAG)) {
					Log.d(GET_TAG, "OnResume result ok");
					fillSpotsList();
				} else {
					Log.d(GET_TAG, "OnResume result fail");
					spotsListFuilure();
				}
			else {
				Log.d(GET_TAG, "OnResume get spots");
				getSpotsList();
			}
		}
		
		mContext.registerReceiver(favReceiver, new IntentFilter(FAV_TAG));

		mContext.registerReceiver(reportReceiver, new IntentFilter(REPORT_TAG));

	

		if (ConnectionUtils.wasConnected(mContext, FAV_TAG))
			// connection was successful
			if (ConnectionUtils.isResultSuccessful(mContext, FAV_TAG))
				favReceiver.onSuccess();
			else
				favReceiver.onFailure();

		if (ConnectionUtils.wasConnected(mContext, REPORT_TAG))
			// connection was successful
			if (ConnectionUtils.isResultSuccessful(mContext, REPORT_TAG))
				reportReceiver.onSuccess();
			else
				reportReceiver.onFailure();

		super.onResume();
	}

	@Override
	public void onDestroy() {
		if (!ConnectionUtils.isConnecting(mContext, GET_TAG))
			ConnectionUtils.clearConnection(mContext, GET_TAG);
		super.onDestroy();
	}

	/**
	 * list of spots received
	 */
	public void fillSpotsList() {
		getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
				false);
		listPart.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.GONE);

		String josnList = ConnectionUtils.getExtra(mContext, GET_TAG);
		if (josnList == null) {
			Log.e(GET_TAG, "emptylist");
			return;
		}
		try {
			ArrayList<Spot> spots = new ArrayList<Spot>();
			JSONArray spotslist = new JSONArray(josnList);
			for (int i = 0; i < spotslist.length(); i++) {
				spots.add(Spot.createFromJSON(spotslist.getJSONObject(i)));
			}
			Log.d(GET_TAG, "spots list loaded from online " + spots.size());
			adapter.updateEntries(spots);

		} catch (JSONException e) {

			e.printStackTrace();
		}

	}

	/**
	 * fail to get spots
	 */
	public void spotsListFuilure() {
		getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
				false);
		progressBar.setVisibility(View.GONE);
		retryBtn.setVisibility(View.VISIBLE);
		Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, GET_TAG),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, GET_TAG);
	}

	/**
	 * firing service to get spots list
	 */
	public void getSpotsList() {
		if (!ConnectionUtils.isNetworkAvailable(mContext)) // {
			// No connection
			ConnectionUtils.showNoConnectionDialog(mContext);
		if (isVisible()) {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
			listPart.setVisibility(View.GONE);
			progressBar.setVisibility(View.VISIBLE);
		}
		startSpotsListService();

	}

	public void startSpotsListService() {

		Intent backgroud_regService = new Intent(mContext,
				SpotsListService.class);
		backgroud_regService.setAction(GET_TAG);
		backgroud_regService.putExtra(HTTPService.LOGIN_RQUIRED, true);
		backgroud_regService.putExtra(SpotsListService.LIST_TYPE, 2);
		mContext.startService(backgroud_regService);
		Log.e("Fragment", "Fired spots service");

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		// getting the active spot
		android.view.MenuInflater inflater = getActivity().getMenuInflater();// getSherlockActivity().getSupportMenuInflater();
		inflater.inflate(R.menu.favorite_spots_context_menu, menu);
		Spot spot = adapter.getmEntries().get(info.position);

		// remove Report
		if (!spot.isCreator())
			menu.removeItem(R.id.report);

	}

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();

		Spot spot = adapter.getmEntries().get(info.position);
		switch (item.getItemId()) {
		case R.id.unfavorite:
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
			spot.toggleFavorite(mContext, false,FAV_TAG);
			return true;
		case R.id.report:
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
			spot.report(mContext,REPORT_TAG);
			return true;

		}
		return super.onContextItemSelected(item);
		// return super.onContextItemSelected(item);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			reloadList();
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * reloads the spot list of this fragment
	 */
	public void reloadList() {
		getSpotsList();
	}

}
